package com.sws.orderMS;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.sws.orderMS.command.Command;
import com.sws.orderMS.command.CommandFactory;
import com.sws.orderMS.command.CommandFactory.CommandCode;
import com.sws.orderMS.pojo.User;
import com.sws.orderMS.tool.Tool;

public class OrderMSApplication {

	private static long orderNum = 0;
	private static String date;
	private User userProfile;
	
	private static OrderMSApplication instance;
	
	private OrderMSApplication() {
	}
	
	public static synchronized OrderMSApplication getInstance() {
		if (instance == null) {
			instance = new OrderMSApplication();
		}
		return instance;
	}
	
	public static void main(String[] args) {
		Tool.printMsg("====== 订单管理系统  ======");
		Tool.printMsg("You can use the \"HELP\" for command usage.");
		
		while (true) {
			String cmd = Tool.askUserInputNotNull("cmd > ");
			CommandCode cmdCode = null;
			
			try {
				cmdCode = CommandCode.valueOf(cmd.toUpperCase());
			} catch (Exception e) {
				Tool.printMsg("Please enter a valid command");
				continue;
			}
			
			User user = OrderMSApplication.getInstance().getUserProfile();
			CommandFactory commandFactory = 
					CommandFactory.buildFactory(user);
			Command command = commandFactory.buildCommand(cmdCode);
			if (command != null) {
				command.execute();
			}
			
		}
	}

	public User getUserProfile() {
		return userProfile;
	}
	
	public void setUserProfile(User user) {
		this.userProfile = user;
	}
	
	public static synchronized long getOrderNo() {
		String str = new SimpleDateFormat("MMddHHmm").format(new Date());
		if (date == null || !date.equals(str)) {
			date = str;
			orderNum = 01;
		} else {
			orderNum++;
		}
		long orderNo = (Long.parseLong(date) * 10 + orderNum) * 100;
		return orderNo;
	}
	
}
